package com.tencreat.service.account.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.domain.BaseEntity;
import com.tencreat.common.core.domain.model.LoginUser;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.enums.BalanceBusinessType;
import com.tencreat.common.enums.UserType;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.DictUtils;
import com.tencreat.common.utils.TenCreatUtil;
import com.tencreat.common.utils.bean.UserBalanceChange;
import com.tencreat.common.utils.http.HttpClient;
import com.tencreat.common.utils.pay.SDKUtil;
import com.tencreat.domain.account.AccountWithdrawAudit;
import com.tencreat.domain.account.AccountWithdrawInfo;
import com.tencreat.domain.account.CommonWithdrawConfig;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.account.dto.AccountWithdrawInfoDTO;
import com.tencreat.domain.account.dto.ApiWithdrawDTO;
import com.tencreat.mapper.account.AccountWithdrawInfoMapper;
import com.tencreat.mq.BalanceChangeConsumer;
import com.tencreat.service.account.IAccountWithdrawAuditService;
import com.tencreat.service.account.IAccountWithdrawInfoService;
import com.tencreat.service.account.ICommonWithdrawConfigService;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.mall.impl.PayServiceImpl;
import com.upay.sdk.cashier.bindcard.builder.BindCardBuilder;
import com.upay.sdk.cashier.bindcard.builder.BindCardConfirmBuilder;
import com.upay.sdk.cashier.bindcard.builder.BindCardKaptchaBuilder;
import com.upay.sdk.cashier.bindcard.builder.UnBindCardBuilder;
import com.upay.sdk.cashier.bindcard.executer.BindCardExecuter;
import com.upay.sdk.exception.HmacVerifyException;
import com.upay.sdk.exception.RequestException;
import com.upay.sdk.exception.ResponseException;
import com.upay.sdk.exception.UnknownException;
import com.upay.sdk.executer.ResultListenerAdpater;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户提现基础信息Service业务层处理
 *
 * @author tencreat
 * @date 2021-11-25
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AccountWithdrawInfoServiceImpl extends ServiceImpl<AccountWithdrawInfoMapper, AccountWithdrawInfo> implements IAccountWithdrawInfoService {

    private final IMallUserService mallUserService;
    private final ICommonWithdrawConfigService withdrawConfigService;

    /**
     * 查询用户提现基础信息
     *
     * @param id 用户提现基础信息ID
     * @return 用户提现基础信息
     */
    @Override
    public AccountWithdrawInfo selectAccountWithdrawInfoById(ReqIdParam id) {
        return baseMapper.selectById(id.getId());
    }

    /**
     * 查询用户提现基础信息列表
     *
     * @param accountWithdrawInfo 用户提现基础信息
     * @return 用户提现基础信息
     */
    @Override
    public List<AccountWithdrawInfo> selectAccountWithdrawInfoList(AccountWithdrawInfo accountWithdrawInfo) {
        return baseMapper.selectList(Wrappers.query(accountWithdrawInfo));
    }

    /**
     * 新增用户提现基础信息
     *
     * @param accountWithdrawInfo 用户提现基础信息
     * @return 结果
     */
    @Override
    public int insertAccountWithdrawInfo(AccountWithdrawInfo accountWithdrawInfo) {
        accountWithdrawInfo.setCreateTime(LocalDateTime.now());
        return baseMapper.insert(accountWithdrawInfo);
    }

    /**
     * 修改用户提现基础信息
     *
     * @param accountWithdrawInfo 用户提现基础信息
     * @return 结果
     */
    @Override
    public int updateAccountWithdrawInfo(AccountWithdrawInfo accountWithdrawInfo) {
        accountWithdrawInfo.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(accountWithdrawInfo);
    }

    /**
     * 批量删除用户提现基础信息
     *
     * @param ids 需要删除的用户提现基础信息ID
     * @return 结果
     */
    @Override
    public int deleteAccountWithdrawInfoByIds(ReqIdsParam ids) {
        return baseMapper.deleteBatchIds(ids.getId());
    }

    /**
     * 删除用户提现基础信息信息
     *
     * @param id 用户提现基础信息ID
     * @return 结果
     */
    @Override
    public int deleteAccountWithdrawInfoById(ReqIdParam id) {
        return baseMapper.deleteById(id.getId());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public HttpResult<String> withdraw(ApiWithdrawDTO vo, LoginUser loginUser) {
        Long uuid = loginUser.getAccountLogin().getUuid();

        MallUser one = mallUserService.lambdaQuery().eq(MallUser::getUuid, uuid).one();
        if (StringUtils.isBlank(one.getPayPassword())) {
            return HttpResult.error("请先设置支付密码");
        }
        if (!vo.getPassword().equals(one.getPayPassword())) {
            return HttpResult.error("密码错误");
        }

        if (vo.getAmount().compareTo(BigDecimal.ZERO) < 0) {
            return HttpResult.error("金额不能小于0");
        }
        //现有余额
        BigDecimal balance = one.getBalance();
        if (vo.getType() == 1) {
            if (balance.compareTo(vo.getAmount()) < 0) {
                return HttpResult.error("余额不足");
            }
        }
        CommonWithdrawConfig commonWithdrawConfig = selectWithdrawInfo(1,vo.getUserType());

        if (commonWithdrawConfig.getIsHundredWithdraw() == 1) {
            BigDecimal yu = vo.getAmount().divideAndRemainder(BigDecimal.valueOf(100))[1];
            if (BigDecimal.ZERO.compareTo(yu) != 0) {
                return HttpResult.error("请输入整百的金额");
            }
        }

        if (commonWithdrawConfig.getMinWithdraw().compareTo(vo.getAmount()) > 0) {
            return HttpResult.error("最低提现" + commonWithdrawConfig.getMinWithdraw());
        }

        if (balance.subtract(vo.getAmount()).compareTo(commonWithdrawConfig.getMinKeep()) < 0) {
            return HttpResult.error("最低需保留" + commonWithdrawConfig.getMinWithdraw());
        }

        try {
            sendBalanceMessageAsync(uuid, vo.getAmount().negate(), "2", BalanceBusinessType.WITHDRAW, "");
        } catch (Exception e) {
            throw new CustomException("提现失败");
        }

        return HttpResult.ok();
    }

    public void sendBalanceMessageAsync(Long uuid, BigDecimal amount, String type, BalanceBusinessType use, String remark) throws Exception {
        log.info("同步变动余额----------UUID：{},type:{},amount:{},use:{}，auctionPay：{}，remark：{}-------", uuid, type, amount, use.getDesc(), remark);
        if (amount.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        //修改用户余额
        UserBalanceChange message = new UserBalanceChange();
        message.setUuid(uuid);
        message.setChangAmount(amount);
        message.setType(type);
        message.setBusinessType(use);
        message.setRemark(remark);
        // 发送余额变动消息
        BalanceChangeConsumer balanceChangeConsumer = SpringUtil.getBean(BalanceChangeConsumer.class);
        balanceChangeConsumer.doJobAsync(message);
    }

    @Override
    public CommonWithdrawConfig selectWithdrawInfo(Integer type, UserType userType) {
        return withdrawConfigService.lambdaQuery().eq(CommonWithdrawConfig::getType, type).eq(CommonWithdrawConfig::getUserType,userType).one();
    }

    /**
     * 绑定首信易银行卡
     *
     * @param dto
     * @return 结果
     * @Author lx
     * @Date: 2022/07/01 07:03
     */
    @Override
    public Object bandCart(AccountWithdrawInfoDTO dto) {
        // 查询这张银行卡是否绑定过
        dto.setType(1L);
        AccountWithdrawInfo accountWithdrawInfo = new AccountWithdrawInfo();
        BeanUtils.copyProperties(dto, accountWithdrawInfo);
        AccountWithdrawInfo accountWithdrawInfo1 = baseMapper.selectOne(Wrappers.query(accountWithdrawInfo));
        if (accountWithdrawInfo1 != null && accountWithdrawInfo1.getBindStatus() == 1L) {
            throw new CustomException("该银行卡已被绑定");
        }
        // 查询用户信息
        MallUser mallUser = mallUserService.lambdaQuery().eq(MallUser::getUuid, accountWithdrawInfo.getUserId()).one();
        if (mallUser == null) {
            throw new CustomException("用户信息有误");
        }
        Map<String, String> payConfig = PayServiceImpl.sxyPayConfig();
        if (payConfig == null || payConfig.size() <= 0) {
            throw new CustomException("支付配置有误");
        }
        BindCardBuilder builder = new BindCardBuilder(payConfig.get("merchant_id"));
        builder.setMerchantUserId(mallUser.getUuid() + "")
                .setBankCardNumber(accountWithdrawInfo.getBankCode())
                .setPhoneNumber(accountWithdrawInfo.getBankTelPhone())
                .setName(mallUser.getRealName())
                //.setName("田子妍")
                .setIdCardNum(mallUser.getIdCard())
                //.setBankCardCvv(bankCardCvv)
                //.setValidTerm(validTerm)
                //.setBindCardCallbackUrl("")
                .setBindCardNotifyUrl(payConfig.get("bank_botify_url"));

        BindCardExecuter executer = new BindCardExecuter();
        final JSONObject data = new JSONObject();
        try {
            executer.bothBindCard(builder, new ResultListenerAdpater() {
                @Override
                public void success(com.alibaba.fastjson15.JSONObject jsonObject) {
                    String result = jsonObject.toJSONString();
                    log.info("绑定银行卡返回数据--------------------" + result);
                    if (jsonObject.getString("bindStatus") != null && jsonObject.getString("bindStatus").equals("FAIL")) {
                        throw new CustomException(jsonObject.getString("errorMsg") != null ? jsonObject.getString("errorMsg") : "绑卡失败");
                    }
                    if (jsonObject.getString("bindCardId") != null) {
                        accountWithdrawInfo.setCardName(mallUser.getRealName());
                        accountWithdrawInfo.setBindCardId(jsonObject.getString("bindCardId"));
                        accountWithdrawInfo.setBindStatus(0L);
                        accountWithdrawInfo.setType(1L);
                        if (accountWithdrawInfo1 != null) {
                            accountWithdrawInfo.setId(accountWithdrawInfo1.getId());
                            baseMapper.updateById(accountWithdrawInfo);
                        } else {
                            baseMapper.insert(accountWithdrawInfo);
                        }
                        data.put("id", accountWithdrawInfo.getId());
                    }
                }
            });
        } catch (ResponseException e) {
            log.error("响应异常</br>" + e.toString());
            throw new CustomException("响应异常");
        } catch (HmacVerifyException e) {
            log.error("签名验证异常</br>" + e.toString());
            throw new CustomException("签名验证异常");
        } catch (RequestException e) {
            log.error("请求异常</br>" + e.toString());
            throw new CustomException("请求异常</br>");
        } catch (UnknownException e) {
            log.error("未知异常</br>" + e.toString());
            if (e.getCause() != null && e.getCause().toString().contains("已绑定")) {
                throw new CustomException("银行卡已被绑定");
            }
            throw new CustomException(e.getCause().getMessage());
        }

        return data;
    }

    /**
     * 绑定银行卡确认
     *
     * @param kaptchaCode
     * @param id
     * @return 结果
     * @Author lx
     * @Date: 2022/07/01 07:04
     */
    @Override
    public Object confirmBandCart(String kaptchaCode, Long id) {
        AccountWithdrawInfo accountWithdrawInfo = baseMapper.selectById(id);
        if (accountWithdrawInfo == null) {
            throw new CustomException("支付账号信息有误");
        }
        String merchantId = DictUtils.getDictValue("sxy_pay", "merchant_id");
        BindCardConfirmBuilder builder = new BindCardConfirmBuilder(merchantId);
        builder.setBindCardId(accountWithdrawInfo.getBindCardId())
                .setMerchantUserId(accountWithdrawInfo.getUserId() + "")
                .setKaptchaCode(kaptchaCode);
        BindCardExecuter executer = new BindCardExecuter();
        final JSONObject data = new JSONObject();
        try {
            executer.bothBindCardConfirm(builder, new ResultListenerAdpater() {
                @Override
                public void success(com.alibaba.fastjson15.JSONObject jsonObject) {
                    String result = jsonObject.toJSONString();
                    log.info("绑定银行卡确认返回数据---------------------" + result);
                    data.put("id", id);
                }
            });
        } catch (ResponseException e) {
            log.error("响应异常</br>" + e.toString());
            throw new CustomException("响应异常");
        } catch (HmacVerifyException e) {
            log.error("签名验证异常</br>" + e.toString());
            throw new CustomException("签名验证异常");
        } catch (RequestException e) {
            log.error("请求异常</br>" + e.toString());
            throw new CustomException("请求异常</br>");
        } catch (UnknownException e) {
            log.error("未知异常</br>" + e.toString());
            throw new CustomException("未知异常");
        }

        return data;
    }

    /**
     * 重发验证码
     *
     * @param id
     * @return 结果
     * @Author lx
     * @Date: 2022/07/04 01:44
     */
    @Override
    public Object getKaptcha(Long id) {
        AccountWithdrawInfo accountWithdrawInfo = baseMapper.selectById(id);
        if (accountWithdrawInfo == null) {
            throw new CustomException("支付账号信息有误");
        }
        String merchantId = DictUtils.getDictValue("sxy_pay", "merchant_id");
        BindCardKaptchaBuilder builder = new BindCardKaptchaBuilder(merchantId);
        builder.setBindCardId(accountWithdrawInfo.getBindCardId());
        BindCardExecuter executer = new BindCardExecuter();
        final JSONObject data = new JSONObject();
        try {
            executer.bothBindCardKaptcha(builder, new ResultListenerAdpater() {
                @Override
                public void success(com.alibaba.fastjson15.JSONObject jsonObject) {
                    String result = jsonObject.toJSONString();
                    log.info("发送验证码返回数据---------------------" + result);
                    data.put("id", id);
                }
            });
        } catch (ResponseException e) {
            log.error("响应异常</br>" + e.toString());
            throw new CustomException("响应异常");
        } catch (HmacVerifyException e) {
            log.error("签名验证异常</br>" + e.toString());
            throw new CustomException("签名验证异常");
        } catch (RequestException e) {
            log.error("请求异常</br>" + e.toString());
            throw new CustomException("请求异常</br>");
        } catch (UnknownException e) {
            log.error("未知异常</br>" + e.toString());
            throw new CustomException("未知异常");
        }

        return data;
    }

    /**
     * 解绑
     *
     * @param id
     * @return 结果
     * @Author lx
     * @Date: 2022/07/04 01:44
     */
    @Override
    public Object unbind(Long id) {
        AccountWithdrawInfo accountWithdrawInfo = baseMapper.selectById(id);
        if (accountWithdrawInfo == null) {
            throw new CustomException("支付账号信息有误");
        }
        String merchantId = DictUtils.getDictValue("sxy_pay", "merchant_id");
        UnBindCardBuilder builder = new UnBindCardBuilder(merchantId);
        builder.setBindCardId(accountWithdrawInfo.getBindCardId())
                .setMerchantUserId(accountWithdrawInfo.getUserId() + "");

        BindCardExecuter executer = new BindCardExecuter();
        final JSONObject data = new JSONObject();
        try {
            executer.bothUnbindCard(builder, new ResultListenerAdpater() {
                @Override
                public void success(com.alibaba.fastjson15.JSONObject jsonObject) {
                    String result = jsonObject.toJSONString();
                    log.info("解绑银行卡返回数据---------------------" + result);
                    accountWithdrawInfo.setBindStatus(0L);
                    baseMapper.updateById(accountWithdrawInfo);
                    data.put("id", id);
                }
            });
        } catch (ResponseException e) {
            log.error("响应异常</br>" + e.toString());
            throw new CustomException("响应异常");
        } catch (HmacVerifyException e) {
            log.error("签名验证异常</br>" + e.toString());
            throw new CustomException("签名验证异常");
        } catch (RequestException e) {
            log.error("请求异常</br>" + e.toString());
            throw new CustomException("请求异常</br>");
        } catch (UnknownException e) {
            log.error("未知异常</br>" + e.toString());
            throw new CustomException("未知异常");
        }

        return data;
    }


    /**
     * 绑定银行卡  杉德
     *
     * @param dto
     * @return 结果
     * @Author lx
     * @Date: 2022/07/01 07:03
     */
    @Override
    public Object sandBandCart(AccountWithdrawInfoDTO dto) {
        AccountWithdrawInfo accountWithdrawInfo = new AccountWithdrawInfo();
        BeanUtils.copyProperties(dto, accountWithdrawInfo);
        // 查询这张银行卡是否绑定过
        AccountWithdrawInfo withdrawInfo = new AccountWithdrawInfo();
        withdrawInfo.setType(2L);
        withdrawInfo.setUserId(accountWithdrawInfo.getUserId());
        withdrawInfo.setBankCode(accountWithdrawInfo.getBankCode());
        AccountWithdrawInfo accountWithdrawInfo1 = baseMapper.selectOne(Wrappers.query(withdrawInfo));
        if (accountWithdrawInfo1 != null && accountWithdrawInfo1.getBindStatus() == 1L) {
            throw new CustomException("该银行卡已被绑定");
        }
        // 查询用户信息
        MallUser mallUser = mallUserService.lambdaQuery().eq(MallUser::getUuid, accountWithdrawInfo.getUserId()).one();
        if (mallUser == null) {
            throw new CustomException("用户信息有误");
        }
        if (StringUtils.isEmpty(mallUser.getRealName()) || StringUtils.isEmpty(mallUser.getIdCard())) {
            throw new CustomException("请先进行实名认证，再绑卡");
        }
        accountWithdrawInfo.setCardName(mallUser.getRealName());
        accountWithdrawInfo.setBindStatus(0L);
        accountWithdrawInfo.setType(2L);
        accountWithdrawInfo.setPayNo(TenCreatUtil.getInfoNo());
        // 组后台报文
        JSONObject head = new JSONObject();
        head.put("version", "1.0");
        head.put("method", "sandPay.fastPay.apiPay.applyBindCard");
        head.put("productId", "00000018");
        head.put("accessType", "1");
        head.put("mid", "6888805045643");
        head.put("channelType", "08");
        head.put("reqTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        JSONObject body = new JSONObject();
        body.put("userId", accountWithdrawInfo.getUserId());
        //body.put("clearCycle", map.get("clearCycle"));
        body.put("applyNo", accountWithdrawInfo.getPayNo());
        body.put("cardNo", accountWithdrawInfo.getBankCode());
        body.put("userName", mallUser.getRealName());
        body.put("phoneNo", accountWithdrawInfo.getBankTelPhone());
        body.put("certificateType", "01");
        body.put("certificateNo", mallUser.getIdCard());
        body.put("creditFlag", "1");
        JSONObject data = new JSONObject();
        data.put("head", head);
        data.put("body", body);
        JSONObject resultData = new JSONObject();
        try {
            // 报文签名
            String reqSign = PayServiceImpl.digitalSignShanDe(data.toJSONString());
            //整体报文格式
            Map<String, String> reqMap = new HashMap<String, String>();
            reqMap.put("charset", "UTF-8");
            reqMap.put("data", JSON.toJSONString(data));
            reqMap.put("signType", "01");
            reqMap.put("sign", reqSign);
            reqMap.put("extend", "");

            log.info("协议支付绑卡请求报文----数据：\n" + JSONObject.toJSONString(JSON.toJSONString(data)));
            log.info("协议支付绑卡请求报文----签名：\n" + JSONObject.toJSONString(reqSign));
            String result = HttpClient.doPost("https://cashier.sandpay.com.cn/fastPay/apiPay/applyBindCard", reqMap, 300000, 600000);
            log.info("协议支付绑卡响应报文：\n" + result);
            result = URLDecoder.decode(result, "UTF-8");
            Map<String, String> respMap = SDKUtil.convertResultStringToMap(result);
            log.info("协议支付绑卡响应报文: {}", respMap);
            String respData = respMap.get("data");
            JSONObject jsonObject = JSONObject.parseObject(respData);
            String body1 = jsonObject.getString("body");
            String head1 = jsonObject.getString("head");
            JSONObject head12 = JSONObject.parseObject(head1);
            if (StringUtils.isNotEmpty(body1)) {
                JSONObject object = JSONObject.parseObject(body1);
                if (StringUtils.isEmpty(object.getString("sdMsgNo"))) {
                    throw new CustomException(head12.getString("respMsg"));
                }
                log.info("第三方绑定编号----------" + head12.getString("respMsg"));
                accountWithdrawInfo.setBindCardId(object.getString("sdMsgNo"));
                if (accountWithdrawInfo1 != null) {
                    accountWithdrawInfo.setId(accountWithdrawInfo1.getId());
                    baseMapper.updateById(accountWithdrawInfo);
                } else {
                    baseMapper.insert(accountWithdrawInfo);
                }
                resultData.put("id", accountWithdrawInfo.getId());
            } else {
                throw new CustomException(head12.getString("respMsg"));
            }
        } catch (Exception e) {
            // log.error("报错-------"+e.getMessage());
            throw new CustomException(e.getMessage());
        }

        return resultData;
    }

    /**
     * 绑定银行卡确认 杉德
     *
     * @param kaptchaCode
     * @param id
     * @return 结果
     * @Author lx
     * @Date: 2022/07/19 10:48
     */
    @Override
    public Object sandConfirmBandCart(String kaptchaCode, Long id) {
        AccountWithdrawInfo accountWithdrawInfo = baseMapper.selectById(id);
        if (accountWithdrawInfo == null) {
            throw new CustomException("支付账号信息有误");
        }
        // 组后台报文
        JSONObject head = new JSONObject();
        head.put("version", "1.0");
        head.put("method", "sandPay.fastPay.apiPay.confirmBindCard");
        head.put("productId", "00000018");
        head.put("accessType", "1");
        head.put("mid", "6888805045643");
        head.put("channelType", "08");
        head.put("reqTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        JSONObject body = new JSONObject();
        body.put("userId", accountWithdrawInfo.getUserId());
        body.put("sdMsgNo", accountWithdrawInfo.getBindCardId());
        body.put("phoneNo", accountWithdrawInfo.getBankTelPhone());
        body.put("smsCode", kaptchaCode);
        JSONObject data = new JSONObject();
        data.put("head", head);
        data.put("body", body);
        JSONObject resultData = new JSONObject();
        try {
            // 报文签名
            String reqSign = PayServiceImpl.digitalSignShanDe(data.toJSONString());
            //整体报文格式
            Map<String, String> reqMap = new HashMap<String, String>();
            reqMap.put("charset", "UTF-8");
            reqMap.put("data", JSON.toJSONString(data));
            reqMap.put("signType", "01");
            reqMap.put("sign", reqSign);
            reqMap.put("extend", "");


            log.info("请求报文----数据：\n" + JSONObject.toJSONString(JSON.toJSONString(data)));
            log.info("请求报文----签名：\n" + JSONObject.toJSONString(reqSign));
            String result = HttpClient.doPost("https://cashier.sandpay.com.cn/fastPay/apiPay/confirmBindCard", reqMap, 300000, 600000);
            result = URLDecoder.decode(result, "UTF-8");
            log.info("响应报文：\n" + result);
            Map<String, String> respMap = SDKUtil.convertResultStringToMap(result);
            String respData = respMap.get("data");
            JSONObject jsonObject = JSONObject.parseObject(respData);
            String body1 = jsonObject.getString("body");
            String head1 = jsonObject.getString("head");
            if (StringUtils.isNotEmpty(body1)) {
                JSONObject object = JSONObject.parseObject(body1);
                if (StringUtils.isEmpty(object.getString("bid"))) {
                    JSONObject head2 = JSONObject.parseObject(head1);
                    throw new CustomException(head2.getString("respMsg"));
                }
                accountWithdrawInfo.setBindStatus(1L);
                accountWithdrawInfo.setBindCardId(object.getString("bid"));
                accountWithdrawInfo.setId(accountWithdrawInfo.getId());
                baseMapper.updateById(accountWithdrawInfo);

                resultData.put("id", accountWithdrawInfo.getId());
                resultData.put("bid", object.getString("bid"));
            }
        } catch (Exception e) {
            // log.error(e.getMessage());
            throw new CustomException(e.getMessage());
        }

        return resultData;
    }
}
